#! /usr/bin/env python3
# -*-coding: utf-8-*-

"""
Created on Apr 7 2017

@author: Moonkie

@attention: Nothing I want to write here.
"""


import os
import shutil


ROOT = os.path.dirname(__file__)
DATASETS = os.path.join(ROOT,'datasets')
DB = os.path.join(DATASETS,'imgso.db')
FACE_DIR = os.path.join(DATASETS,'faces')
FACE_FEATURE_DIR = os.path.join(DATASETS,'features')
IMAGES = os.path.join(DATASETS,'images')
SOURCES = os.path.join(DATASETS,'sources')
TEMP = os.path.join(ROOT,'webforce','static','temp')


CREATETABLECHIPS = 'CREATE TABLE IF NOT EXISTS chips(\
                    id INTEGER PRIMARY KEY AUTOINCREMENT,\
                    chip TEXT UNIQUE NOT NULL,\
                    source TEXT NOT NULL,\
                    feature TEXT NOT NULL);'

CREATETABLEPEOPLE = 'CREATE TABLE IF NOT EXISTS people(\
                    id INTEGER PRIMARY KEY AUTOINCREMENT,\
                    source TEXT UNIQUE NOT NULL,\
                    name TEXT,\
                    sex TEXT,\
                    profession TEXT,\
                    baike TEXT);'

def make_dataset_full():
    os.makedirs(DATASETS)
    os.mkdir(FACE_DIR)
    os.mkdir(FACE_FEATURE_DIR)
    os.mkdir(IMAGES)


if not os.path.exists(DATASETS):
    make_dataset_full()
else:
    if os.path.isfile(DATASETS):
        shutil.move(DATASETS,DATASETS+'~')
        make_dataset_full()
    else:
        try:
            os.mkdir(FACE_DIR)
        except:
            pass
        try:
            os.mkdir(FACE_FEATURE_DIR)
        except:
            pass
        try:
            os.mkdir(IMAGES)
        except:
            pass
        try:
            os.mkdir(SOURCES)
        except:
            pass
        try:
            os.mkdir(TEMP)
        except:
            pass
        

if not os.path.exists(DB):
    import sqlite3 as sql
    conn = sql.connect(DB,10)
    cur = conn.cursor()
    try:
        cur.executescript(CREATETABLECHIPS+CREATETABLEPEOPLE)
        conn.commit()
    except Exception as e:
        cur.close()
        conn.close()
        os.unlink(DB)
        raise Exception('Create database %s failure.' % DB )
    
print('[^_^] Initial Successfully!')
        
